<template>
  <div class="student-management-container">
    <!-- 标题区 -->
    <div class="header">
      <h2><i class="el-icon-notebook-2"></i> 学生信息管理系统</h2>
      <div class="operation-buttons">
        <el-button type="success" @click="handleAdd" icon="el-icon-plus">
          添加学生
        </el-button>
      </div>
    </div>

    <!-- 查询卡片 -->
    <el-card class="search-card" shadow="never">
      <el-form :inline="true" :model="form" class="search-form">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" clearable prefix-icon="el-icon-user"></el-input>
        </el-form-item>
        <el-form-item label="学号" prop="number">
          <el-input v-model="form.number" placeholder="请输入学号" clearable prefix-icon="el-icon-tickets"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级" clearable prefix-icon="el-icon-office-building"></el-input>
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" @click="handleSearch" icon="el-icon-search">查询</el-button>
          <el-button @click="resetForm" icon="el-icon-refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

      <!-- 数据表格卡片 -->
  <el-card class="table-card" shadow="never">
    <el-table 
      :data="tableData" 
      border 
      v-loading="loading"
      element-loading-text="数据加载中..."
      element-loading-spinner="el-icon-loading"
      style="width: 100%"
      :fit="true">  <!-- 添加fit属性使列自动填充 -->
      
      <!-- 表格列 - 使用min-width代替固定width -->
      <el-table-column prop="studentId" label="ID" min-width="80" align="center"></el-table-column>
      <el-table-column prop="studentName" label="姓名" min-width="100" align="center"></el-table-column>
      <el-table-column prop="number" label="学号" min-width="120" align="center"></el-table-column>
      <el-table-column prop="className" label="班级" min-width="120" align="center"></el-table-column>
      <el-table-column prop="grade" label="年级" min-width="100" align="center"></el-table-column>
      <el-table-column label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button 
              @click="handleEdit(scope.row)" 
              type="primary" 
              size="mini" 
              icon="el-icon-edit" 
              circle></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button 
              @click="handleDelete(scope.row)" 
              type="danger" 
              size="mini" 
              icon="el-icon-delete" 
              circle></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
  </el-card>
    <!-- 学生表单对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      width="500px"
      :close-on-click-modal="false"
      custom-class="student-dialog">
      <el-form 
        :model="addAndEditForm" 
        :rules="rules" 
        ref="studentForm" 
        label-width="100px"
        label-position="left">
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="addAndEditForm.studentName" placeholder="请输入学生姓名"></el-input>
        </el-form-item>
        <el-form-item label="学号" prop="number">
          <el-input v-model="addAndEditForm.number" placeholder="请输入学号"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-input v-model="addAndEditForm.className" placeholder="请输入班级"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="addAndEditForm.grade" placeholder="请选择年级" style="width:100%">
            <el-option label="23" value="23"></el-option>
            <el-option label="24" value="24"></el-option>
            <el-option label="25" value="25"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="medium">取 消</el-button>
        <el-button type="primary" @click="submitForm" size="medium">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getStudentList, addStudent, editStudent, deleteStudent } from "@/api/student.js";

export default {
  data() {
    return {
      loading: false,
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      form: {
        name: "",
        number: "",
        className: "",
      },
      total: 0,
      dialogVisible: false,
      dialogType: 'add',
      dialogTitle: "添加学生",
      addAndEditForm: {
        studentId: undefined,
        studentName: "",
        number: "",
        className: "",
        grade: ""
      },
      rules: {
        studentName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '请输入学号', trigger: 'blur' },
          { pattern: /^\d{8,12}$/, message: '请输入8-12位数字', trigger: 'blur' }
        ],
        className: [
          { required: true, message: '请输入班级', trigger: 'blur' }
        ],
        grade: [
          { required: true, message: '请选择年级', trigger: 'change' }
        ]
      }
    };
  },
  mounted() {
    this.getStudentList();
  },
  methods: {
    async getStudentList() {
      this.loading = true;
      try {
        const res = await getStudentList({
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          ...this.form,
        });
        this.tableData = res.rows || [];
        this.total = res.total || 0;
      } catch (err) {
        console.error(err);
        this.$message.error('获取学生列表失败');
      } finally {
        this.loading = false;
      }
    },
    handleSearch() {
      this.pageNum = 1;
      this.getStudentList();
    },
    resetForm() {
      this.form = {
        name: "",
        number: "",
        className: "",
      };
      this.handleSearch();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getStudentList();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getStudentList();
    },
    handleAdd() {
      this.dialogType = 'add';
      this.dialogTitle = '添加学生';
      this.addAndEditForm = {
        studentId: undefined,
        studentName: "",
        number: "",
        className: "",
        grade: ""
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.studentForm?.clearValidate();
      });
    },
    handleEdit(row) {
      this.dialogType = 'edit';
      this.dialogTitle = '编辑学生';
      this.addAndEditForm = { ...row };
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm(`确定要删除学生【${row.studentName}】吗？`, "删除确认", {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "el-button--danger"
      }).then(async () => {
        try {
          await deleteStudent({ id: row.studentId });
          this.$message.success("删除成功");
          this.getStudentList();
        } catch (err) {
          console.error(err);
          this.$message.error("删除失败");
        }
      }).catch(() => {
        this.$message.info("已取消删除");
      });
    },
    submitForm() {
      this.$refs.studentForm.validate(async valid => {
        if (valid) {
          try {
            if (this.dialogType === 'add') {
              await addStudent(this.addAndEditForm);
              this.$message.success("添加成功");
            } else {
              await editStudent(this.addAndEditForm);
              this.$message.success("编辑成功");
            }
            this.dialogVisible = false;
            this.getStudentList();
          } catch (err) {
            console.error(err);
            this.$message.error(this.dialogType === 'add' ? "添加失败" : "编辑失败");
          }
        }
      });
    }
  },
};
</script>

<style lang="scss" scoped>
.student-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;

    h2 {
      color: #303133;
      font-size: 20px;
      margin: 0;
      display: flex;
      align-items: center;

      i {
        margin-right: 10px;
        color: #409EFF;
      }
    }
  }

  .search-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: none;

    .search-form {
      display: flex;
      flex-wrap: wrap;

      .el-form-item {
        margin-right: 15px;
        margin-bottom: 15px;
      }

      .search-buttons {
        margin-left: auto;
      }
    }
  }

  .table-card {
    border-radius: 8px;
    border: none;

    .el-table {
      font-size: 14px;

      th {
        background-color: #f8f9fa !important;
        color: #606266;
        font-weight: 600;
      }

      .el-button--mini.is-circle {
        padding: 5px;
      }
    }

    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
}

// 对话框样式
.student-dialog {
  border-radius: 8px;

  .el-dialog__header {
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
    margin-right: 0;
  }

  .el-dialog__body {
    padding: 20px 25px;
  }

  .el-dialog__footer {
    padding: 15px 20px;
    border-top: 1px solid #ebeef5;
  }
}

// 响应式设计
@media (max-width: 992px) {
  .search-form {
    .el-form-item {
      width: 100%;
      margin-right: 0 !important;
    }

    .search-buttons {
      width: 100%;
      display: flex;
      justify-content: flex-end;
    }
  }
}

@media (max-width: 768px) {
  .student-management-container {
    padding: 15px;
  }

  .header {
    flex-direction: column;
    align-items: flex-start !important;

    h2 {
      margin-bottom: 10px !important;
    }
  }

  .operation-buttons {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
}
</style>